﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Ordinaire.Commerce.Db
{
    /// <summary>
    /// Used as helper class that inherits Ordinaire.Commerce.Db.IDatabasePart.
    /// </summary>
    public abstract class DatabasePartHelper : IDatabasePart
    {
        #region Variables

        /// <summary>
        /// Table type.
        /// </summary>
        protected readonly Type tableType = null;

        #endregion

        #region Constructor

        /// <summary>
        /// Returns new instance of DatabasePartHelper.
        /// </summary>
        public DatabasePartHelper()
        {
            this.tableType = typeof(Table<>);
        }

        #endregion

        #region Property methods

        /// <summary>
        /// Gets the type to extract from.
        /// </summary>
        public abstract Type Type { get; }

        #endregion

        #region Public methods

        /// <summary>
        /// Returns list of tables as array of System.Reflection.FieldInfo to create.
        /// </summary>
        /// <returns>array of System.Reflection.FieldInfo representing list of tables used by the extension</returns>
        public FieldInfo[] GetTables()
        {
            Type            fieldType   = null;
            FieldInfo       fieldInfo   = null;
            List<FieldInfo> tables      = new List<FieldInfo>();

            FieldInfo[] fieldInfos = Type.GetFields(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
            int fieldInfosLength = fieldInfos.Length;
            for (int i = 0; i < fieldInfosLength; i++)
            {
                fieldInfo = fieldInfos[i];
                fieldType = fieldInfo.FieldType;
                if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == tableType)
                {
                    tables.Add(fieldInfo);
                }
            }

            return tables.ToArray();
        }

        #endregion
    }
}
